package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import com.cskaoyan.user.utils.SendEmailTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.UUID;

@Service
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper verifyMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${email.text}")
    private String verifyBase;

    @Override
    @Transactional
    public void register(UserRegisterRequest request) {
        String userName = request.getUserName();
        String userPwd = request.getUserPwd();
        String email = request.getEmail();

        // 验证用户名重复
        Example userExample1 = new Example(Member.class);
        userExample1.createCriteria().andEqualTo("username", userName);
        int nameCnt = memberMapper.selectCountByExample(userExample1);
        // 用户名重复，抛出异常
        if (nameCnt > 0) {
            throw new BizException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),
                    UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }

        // 验证邮箱重复
        Example userExample2 = new Example(Member.class);
        userExample2.createCriteria().andEqualTo("email", email);
        int emailCnt = memberMapper.selectCountByExample(userExample2);
        // 邮箱重复，抛出异常
        if (emailCnt > 0) {
            throw new BizException(UserRetCode.EMAIL_ALREADY_EXISTS.getCode(),
                    UserRetCode.EMAIL_ALREADY_EXISTS.getMessage());
        }

        // 插入用户表
        Member member = new Member();
        member.setUsername(userName);
        member.setPassword(DigestUtils.md5DigestAsHex(userPwd.getBytes()));
        member.setEmail(email);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setState(1);
        int rows1 = memberMapper.insertSelective(member);
        if (rows1 != 1) {
            throw new BizException(UserRetCode.USER_REGISTER_FAILED.getCode(),
                    UserRetCode.USER_REGISTER_FAILED.getMessage());
        }

        // 插入验证表
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(userName);
        String uuidKey = userName + userPwd + UUID.randomUUID();
        userVerify.setUuid(DigestUtils.md5DigestAsHex(uuidKey.getBytes()));
        userVerify.setRegisterDate(new Date());
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        int rows2 = verifyMapper.insertSelective(userVerify);
        if (rows2 != 1) {
            throw new BizException(UserRetCode.USER_REGISTER_FAILED.getCode(),
                    UserRetCode.USER_REGISTER_FAILED.getMessage());
        }

        // 发送激活邮件
        SendEmailTask emailTask = new SendEmailTask(mailSender, userVerify, email, verifyBase);
        new Thread(emailTask).start();
    }

    @Override
    @Transactional
    public void verify(UserVerifyRequest request) {
        String uuid = request.getUuid();
        String username = request.getUsername();

        // 更新用户表
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username", username);
        Member member = new Member();
        member.setUpdated(new Date());
        member.setIsVerified("Y");
        int rows1 = memberMapper.updateByExampleSelective(member, memberExample);

        Example verifyExample = new Example(UserVerify.class);
        verifyExample.createCriteria().andEqualTo("username", username)
                .andEqualTo("uuid", uuid);
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        int rows2 = verifyMapper.updateByExampleSelective(userVerify, verifyExample);

        if (rows1 != 1 || rows2 != 1) {
            throw new BizException(UserRetCode.USERVERIFY_INFOR_INVALID.getCode(),
                    UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
        }
    }
}
